import * as vscode from 'vscode';

type BackendStream = 'stdout' | 'stderr' | 'meta';

const MAX_BUFFERED_LINES = 400;
const bufferedLines: string[] = [];

function normalizeChunk(chunk: string): string[] {
    return chunk
        .replace(/\r\n/g, '\n')
        .split(/\n/)
        .map(line => line.trimEnd())
        .filter(line => line.length > 0);
}

function appendLines(lines: string[]) {
    for (const line of lines) {
        bufferedLines.push(line);
        if (bufferedLines.length > MAX_BUFFERED_LINES) {
            bufferedLines.shift();
        }
    }
}

export function recordBackendOutput(chunk: string, stream: BackendStream): void {
    const prefix = stream === 'meta'
        ? '[backend]'
        : stream === 'stderr'
            ? '[backend stderr]'
            : '[backend stdout]';
    const lines = normalizeChunk(chunk).map(line => `${prefix} ${line}`);
    if (lines.length === 0) {
        return;
    }
    appendLines(lines);
}

export function dumpBackendOutput(
    outputChannel: vscode.OutputChannel,
    context?: string,
    limit = 80
): void {
    if (bufferedLines.length === 0) {
        outputChannel.appendLine('ℹ️ No backend output captured yet.');
        return;
    }
    const title = context
        ? `📄 Backend output snapshot (${context})`
        : '📄 Backend output snapshot';
    outputChannel.appendLine(title);
    const slice = bufferedLines.slice(-Math.max(limit, 1));
    for (const line of slice) {
        outputChannel.appendLine(line);
    }
}
